package com.flowerplus.store.common.structure.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.flowerplus.store.common.data.injector.HasComponent;
import com.flowerplus.store.common.data.injector.HasPermission;
import com.flowerplus.store.common.data.utils.SpUtil;
import com.flowerplus.store.common.structure.key.TokenKey;
import com.flowerplus.store.common.structure.mvp.BasePresenter;
import com.tbruyelle.rxpermissions.RxPermissions;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by ems on 2017/2/27.
 */

public abstract class BaseFragment extends Fragment {
    protected View mRootView;
    private BasePresenter mBasePresenter;
    protected Unbinder mBind;
    protected BaseFragment mFragment;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(initContentView(), container, false);
        initStatus();
        mBind = ButterKnife.bind(this, mRootView);
        return mRootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initInjector();

        initViews();
        initData();
        initEvents();

        mBasePresenter = getPresenter();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragment = this;
    }

    protected abstract void initData();

    protected abstract void initEvents();

    protected abstract void initViews();

    public abstract void initInjector();

    public abstract int initContentView();

    protected abstract BasePresenter getPresenter();

    protected void initStatus() {
    }

    @Override
    public void onDestroy() {
        if (mBasePresenter != null) mBasePresenter.onDestroy();
        super.onDestroy();

    }

    @Override
    public void onDestroyView() {
        if (mBind != null) {
            mBind.unbind();
        }
        super.onDestroyView();
    }

    protected <T extends View> T findViewById(int id) {
        return (T) mRootView.findViewById(id);
    }


    @SuppressWarnings("unchecked")
    protected <C> C getComponent(Class<C> componentType) {
        return componentType.cast(((HasComponent<C>) getActivity()).getComponent());
    }

    protected RxPermissions getPermission() {
        return ((HasPermission) getActivity()).getPermission();
    }
    protected boolean hasLogin(){
        return !TextUtils.isEmpty(SpUtil.getInstance().getString(TokenKey.USER_ID));
    }
}
